import { acceptHMRUpdate, defineStore } from "pinia";
import { cloneDeep } from "lodash-es";
import { readPageInfo } from "../service/page";
import { ElMessage } from "element-plus";
import { UUID3 } from "../utils/utils";
import { commonAttr } from "../utils/constant";
import { emitter } from "../utils/emitter.js";
import { createGroupStyle, decomposeComponent } from "../utils/component";

export const useDesignStore = defineStore({
  id: "design",
  state: () => ({
    designTreeShow: true,
    designLibShow: true,
    designConfigShow: true,
    designBarShow: true,
    designMapShow: true,
    isInEdiotr: false,
    // 卡尺指示线信息
    referLine: {
      enable: true,
    },
    /** 快照 */
    snapshotIndex: -1, // 快照索引
    snapshotData: [], // 编辑器快照数据
    /** 页面信息 */
    pageFilters: {},
    pageComponents: [],
    pageInfo: {},
    pageConfig: {},
    /** 页面信息 end*/
    curComponent: {},
    curComponentIndex: -1,
    isClickComponent: false,
    /** 组件右击菜单 start */
    menuTop: 0,
    menuLeft: 0,
    menuShow: false,
    /** 组件右击菜单 end */
    /** 复制粘贴 */
    copyData: null,
    isCut: false,
    /** 选中区域 */
    areaData: {
      attr: {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
        rotate: 0,
        opacity: 1,
        borderRadius: 0,
        borderStyle: "solid",
        borderWidth: 0,
        bgColor: "transparent",
      },
      components: []
    },
    /**选中区域 */
    editor: null
  }),
  actions: {
    /** 页面配置操作 start */

    // 组件树面板 
    setDesignTreeShow (flag) {
      this.designTreeShow = !flag;
    },

    // 关闭组件树面板 
    closeDesignTreeShow () {
      this.designTreeShow = false;
    },

    // 元件库面板 
    setDesignLibShow (lib) {
      this.designLibShow = !lib;
    },

    // 关闭元件库面板 
    closeDesignLibShow () {
      this.designLibShow = false;
    },

    // 元件数据配置面板 
    setDesignConfigShow (flag) {
      this.designConfigShow = !flag;
    },

    // 设计面板工具栏 
    setDesignBarShow (flag) {
      this.designBarShow = !flag;
    },

    // 设计面板小地图
    setDesignMapShow (show) {
      this.designMapShow = show;
    },

    // 对齐线控制
    setReferLineShow () {
      this.referLine.enable = !!!this.referLine.enable;
    },

    /** 页面配置操作 end */

    /** 页面加载 请求后台信息操作  */

    loadScreen (page_url) {
      return new Promise((resolve, reject) => {
        readPageInfo({ page_url }).then((res) => {
          if (res.code === 0) {
            let json = JSON.parse(res.data.result);
            const {
              pageComponents = [],
              pageConfig = {},
              pageInfo = {},
              pageFilters = [],
            } = json;
            this.setPageFilters(pageFilters);
            this.setPageComponents(pageComponents);
            this.setPageConfig(pageConfig);
            this.setPageInfo(pageInfo);
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    // 加载页面筛选信息
    setPageFilters (pageFilters) {
      this.pageFilters = pageFilters;
    },

    // 加载页面组件信息
    setPageComponents (pageComponents = []) {
      this.pageComponents = pageComponents;
    },

    // 加载页面配置信息
    setPageConfig (pageConfig) {
      this.pageConfig = pageConfig;
    },

    // 加载页面信息
    setPageInfo (pageInfo) {
      this.pageInfo = pageInfo;
    },

    /** 页面加载 请求后台信息操作  */

    // scale 設置
    setScale (value) {
      this.pageConfig.scale = value;
    },

    // 是否在編輯器內 
    setInEditorStatus (status) {
      this.isInEdiotr = status
    },

    /** 快照操作 start */

    // 添加快照
    addSnapshot () {
      // 添加新的快照
      this.snapshotData[++this.snapshotIndex] = cloneDeep(this.pageComponents);
      // 在 undo 过程中，添加新的快照时，要将它后面的快照清理掉
      if (this.snapshotIndex < this.snapshotData.length - 1) {
        this.snapshotData = this.snapshotData.slice(0, this.snapshotIndex + 1);
      }
    },

    // 撤销操作
    undoSnapshot () {
      if (this.snapshotIndex >= 0) {
        this.snapshotIndex--;
        const componentData =
          cloneDeep(this.snapshotData[this.snapshotIndex]) || [];
        if (this.curComponent) {
          // 如果当前组件不在 componentData 中，则置空
          const needClean = !componentData.find(
            (component) => this.curComponent.id === component.id
          );
          if (needClean) {
            this.setCurComponent({
              component: null,
              index: null,
            });
          }
        }
        this.setPageComponents(componentData);
      }
    },

    // 反撤销操作
    redoSnapshot () {
      if (this.snapshotIndex < this.snapshotData.length - 1) {
        this.snapshotIndex++;
        store.commit(
          "setComponentData",
          cloneDeep(this.snapshotData[this.snapshotIndex])
        );
      }
    },
    /** 快照操作 end */

    /** 右键菜单 start */
    showContextMenu ({top, left}) {
      this.menuShow = true;
      this.menuTop = top;
      this.menuLeft = left;
    },

    hideContextMenu () {
      this.menuShow = false;
    },
    /** 右键菜单 end */

    /** 组件操作: 添加 删除 复制 粘贴 剪贴  start*/

    // 组件点击
    setClickComponentStatus (status) {
      this.isClickComponent = status;
    },

    // 设置当前点击组件
    setCurComponent (curItem) {
      this.curComponent = curItem.component;
      this.curComponentIndex = curItem.index;
    },

    // 添加组件
    addComponent ({ component, index }) {
      if (index !== undefined) {
        this.pageComponents.splice(index, 0, component);
      } else {
        this.pageComponents.push(component);
      }
    },

    // 删除组件
    deleteComponent (index) {
      if (index === undefined) {
        index = this.curComponentIndex
      }
      if (index == this.curComponentIndex) {
        this.curComponentIndex = null
        this.curComponent = null
      }
      if (/\d/.test(index)) {
        this.pageComponents.splice(index, 1)
      }
    },

    // 水平翻转
    setCurcomponentFilpH(){
      this.curComponent.attr.filpH = !this.curComponent.attr.filpH 
    },

    //垂直翻转
    setCurcomponentFilpV(){
      this.curComponent.attr.filpV = !this.curComponent.attr.filpV 
    },

    // 组件隱藏
    setCurcomponentHided () {
      if (this.curComponent.id) {
        this.curComponent.hided = true;
      }
    },

    // 组件顯示
    setCurcomponentShow () {
      if (this.curComponent.id) {
        this.curComponent.hided = false;
      }
    },

    // 组件锁定
    setCurcomponentLock () {
      if (this.curComponent.id) {
        this.curComponent.locked = true;
      }
    },

    // 组件解锁
    setCurcomponentUnLock () {
      if (this.curComponent.id) {
        this.curComponent.locked = false;
      }
    },

    // 組件樣式修改
    setShapeStyle ({ top, left, width, height, rotate }) {
      if (top !== undefined || isNaN(top)) this.curComponent.attr.top = top
      if (left !== undefined || isNaN(left) ) this.curComponent.attr.left = left
      if (width !== undefined || isNaN(width) ) this.curComponent.attr.width = width
      if (height !== undefined || isNaN(height) ) this.curComponent.attr.height = height
      if (rotate !== undefined || isNaN(rotate) ) this.curComponent.attr.rotate = rotate
    },


    // 组件复制
    copyCurcomponent () {
      if (!this.curComponent.id) {
        ElMessage({
          message: "请选择组件",
          type: "warning",
        });
        return;
      }
      // 如果有剪切的数据，需要先还原
      if (this.isCut && this.copyData) {
        const data = cloneDeep(this.copyData.data);
        const index = this.copyData.index;
        data.id = UUID3();
        this.addComponent({ component: data, index });
        if (this.curComponentIndex >= index) {
          // 如果当前组件索引大于等于插入索引，需要加一，因为当前组件往后移了一位
          this.curComponentIndex++;
        }
      }
      this.copyData = {
        data: cloneDeep(this.curComponent),
        index: this.curComponentIndex,
      };

      this.isCut = false;
    },

    // 组件粘贴
    pasteComponent (isMouse) {
      if (!this.copyData) {
        ElMessage({
          message: "请选择组件",
          type: "warning",
        });
        return;
      }
      const data = this.copyData.data;
      if (isMouse) {
        data.attr.top = this.menuTop;
        data.attr.left = this.menuLeft;
      } else {
        data.attr.top += 10;
        data.attr.left += 10;
      }

      data.id = UUID3(8);
      // group 的子组件根节点的 id 是通过组件的 id 生成的，必须重新生成 id，否则拆分 Group 的时候获取根节点不正确
      if (data.type === "van-group") {
        data.children.forEach((component) => {
          component.id = UUID3(8);
        });
      }

      this.addComponent({ component: cloneDeep(data) });
      if (this.isCut) {
        this.copyData = null;
      }
    },

    // 组件剪切
    cutCurcomponent () {
      if (!this.copyData) {
        ElMessage({
          message: "请选择组件",
          type: "warning",
        });
        return;
      }
      // 如果重复剪切，需要恢复上一次剪切的数据
      if (this.isCut && this.copyData) {
        const data = cloneDeep(this.copyData.data);
        const index = this.copyData.index;
        data.id = UUID3();
        this.addComponent({ component: data, index });
        if (this.curComponentIndex >= index) {
          // 如果当前组件索引大于等于插入索引，需要加一，因为当前组件往后移了一位
          this.curComponentIndex++;
        }
      }
      this.copyData = {
        data: cloneDeep(this.curComponent),
        index: this.curComponentIndex,
      };

      this.deleteComponent()
      this.isCut = true;
    },
    /** 组件操作: 添加 删除 复制 粘贴 剪贴 end*/

    /** 组件层级操作 start */

    // 上移
    topComponent () {
      if (this.curComponentIndex < this.pageComponents.length - 1) {
        this.pageComponents.splice(this.curComponentIndex + 1, 0, ...this.pageComponents.splice(this.curComponentIndex, 1));
        this.curComponentIndex = this.curComponentIndex + 1
      } else {
        ElMessage({
          message: "已经到顶了",
          type: "warning",
        });
      }
    },

    // 下移
    bottomComponent () {
      // 下移图层 index，表示元素在数组中越往前
      if (this.curComponentIndex > 0) {
        this.pageComponents.splice(this.curComponentIndex - 1, 0, ...this.pageComponents.splice(this.curComponentIndex, 1));
        this.curComponentIndex = this.curComponentIndex - 1
      } else {
        ElMessage({
          message: "已经到底了",
          type: "warning",
        });
      }
    },

    // 置顶
    upComponent () {
      if (this.curComponentIndex < this.pageComponents.length - 1) {
        this.pageComponents.push(...this.pageComponents.splice(this.curComponentIndex, 1));
        this.curComponentIndex = this.pageComponents.length
      } else {
        ElMessage({
          message: "已经到顶了",
          type: "warning",
        });
      }
    },

    // 置底
    downComponent () {
      if (this.curComponentIndex > 0) {
        this.pageComponents.unshift(...this.pageComponents.splice(this.curComponentIndex, 1));
        this.curComponentIndex = 0
      } else {
        ElMessage({
          message: "已经到底了",
          type: "warning",
        });
      }
    },
    /** 组件层级操作 end  */

    // 獲取編輯器
    getEditor () {
      this.editor = document.querySelector("#editor")
    },

    // 獲取選中區域
    setAreaData (data) {
      this.areaData = data
    },

    // 批量刪除
    batchDeleteComponent (deleteData) {
      deleteData.forEach(component => {
        for (let i = 0, len = this.pageComponents.length; i < len; i++) {
          if (component.id == this.pageComponents[i].id) {
            this.pageComponents.splice(i, 1)
            break
          }
        }
      })
    },

    // 合併
    compose () {
      const components = [];
      this.areaData.components.forEach(component => {
        if (component.type != "van-group") {
          components.push(component)
        } else {
          // 如果要组合的组件中，已经存在组合数据，则需要提前拆分
          const parentAttr = { ...component.attr }
          const subComponents = component.children
          const editorRect = editor.getBoundingClientRect()
          subComponents.forEach(component => {
            decomposeComponent(component, editorRect, parentAttr);
          })
          components.push(...component.children)
        }
      })
      const groupComponent = {
        id: UUID3(8),
        ...commonAttr,
        attr: {
          ...this.areaData.attr,
        },
        children: components,
      }
      createGroupStyle(groupComponent);
      this.addComponent({ component: groupComponent, })
      emitter.emit("hideArea");
      // 批量刪除選中區域的組件
      this.batchDeleteComponent(this.areaData.components);
      this.setCurComponent({
        component: this.pageComponents[this.pageComponents.length - 1],
        index: this.pageComponents.length - 1,
      })
      this.areaData.components = []
    },

    // 解除合併
    decompose () {
      const parentAttr = { ...this.curComponent.attr }
      const subComponents = this.curComponent.children
      const editorRect = this.editor.getBoundingClientRect()
      // 刪除當前組件
      this.deleteComponent()
      subComponents.forEach(component => {
        decomposeComponent(component, editorRect, parentAttr);
        this.addComponent({ component })
      })
    },
  },
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: "design",
        storage: localStorage,
      },
    ],
  },
});
// if (import.meta.hot) {
//   import.meta.hot.accept(acceptHMRUpdate(useDesignStore, import.meta.hot))
// }
